package com.cyl.manager.vip.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import com.cyl.manager.act.domain.entity.FhRechargeData;
import com.cyl.manager.act.service.FhRechargeDataService;
import com.cyl.wechat.WechatPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cyl.manager.vip.mapper.VipAutoRenewMapper;
import com.cyl.manager.vip.domain.entity.VipAutoRenew;
import com.cyl.manager.vip.domain.entity.VipOrder;
import com.cyl.manager.vip.service.IVipAutoRenewService;
import com.cyl.manager.vip.service.IVipOrderService;

/**
 * VIP自动续费Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class VipAutoRenewServiceImpl implements IVipAutoRenewService
{
    private static final Logger log = LoggerFactory.getLogger(VipAutoRenewServiceImpl.class);

    @Autowired
    private VipAutoRenewMapper vipAutoRenewMapper;

    @Autowired
    private IVipOrderService vipOrderService;

    @Autowired
    private FhRechargeDataService fhRechargeDataService;

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * 查询VIP自动续费
     *
     * @param id VIP自动续费主键
     * @return VIP自动续费
     */
    @Override
    public VipAutoRenew selectVipAutoRenewById(Long id)
    {
        return vipAutoRenewMapper.selectVipAutoRenewById(id);
    }

    /**
     * 查询VIP自动续费列表
     *
     * @param vipAutoRenew VIP自动续费
     * @return VIP自动续费
     */
    @Override
    public List<VipAutoRenew> selectVipAutoRenewList(VipAutoRenew vipAutoRenew)
    {
        return vipAutoRenewMapper.selectVipAutoRenewList(vipAutoRenew);
    }

    /**
     * 根据用户ID查询有效的自动续费记录
     *
     * @param userId 用户ID
     * @return VIP自动续费
     */
    @Override
    public VipAutoRenew selectVipAutoRenewByUserId(Long userId)
    {
        return vipAutoRenewMapper.selectVipAutoRenewByUserId(userId);
    }

    /**
     * 根据用户ID和充值配置ID查询自动续费记录
     *
     * @param userId 用户ID
     * @param rechargeDataId 充值配置ID
     * @return VIP自动续费
     */
    @Override
    public VipAutoRenew selectVipAutoRenewByUserIdAndRechargeDataId(Long userId, Long rechargeDataId)
    {
        return vipAutoRenewMapper.selectVipAutoRenewByUserIdAndRechargeDataId(userId, rechargeDataId);
    }

    /**
     * 查询需要续费的记录
     *
     * @param currentTime 当前时间
     * @return VIP自动续费集合
     */
    @Override
    public List<VipAutoRenew> selectVipAutoRenewForRenewal(LocalDateTime currentTime)
    {
        return vipAutoRenewMapper.selectVipAutoRenewForRenewal(currentTime);
    }

    /**
     * 新增VIP自动续费
     *
     * @param vipAutoRenew VIP自动续费
     * @return 结果
     */
    @Override
    public int insertVipAutoRenew(VipAutoRenew vipAutoRenew)
    {
        vipAutoRenew.setCreateTime(LocalDateTime.now());
        return vipAutoRenewMapper.insertVipAutoRenew(vipAutoRenew);
    }

    /**
     * 修改VIP自动续费
     *
     * @param vipAutoRenew VIP自动续费
     * @return 结果
     */
    @Override
    public int updateVipAutoRenew(VipAutoRenew vipAutoRenew)
    {
        vipAutoRenew.setUpdateTime(LocalDateTime.now());
        return vipAutoRenewMapper.updateVipAutoRenew(vipAutoRenew);
    }

    /**
     * 更新自动续费状态
     *
     * @param id 自动续费ID
     * @param status 状态
     * @return 结果
     */
    @Override
    public int updateVipAutoRenewStatus(Long id, Integer status)
    {
        return vipAutoRenewMapper.updateVipAutoRenewStatus(id, status);
    }

    /**
     * 增加重试次数
     *
     * @param id 自动续费ID
     * @param failureReason 失败原因
     * @return 结果
     */
    @Override
    public int incrementRetryCount(Long id, String failureReason)
    {
        return vipAutoRenewMapper.incrementRetryCount(id, failureReason);
    }

    /**
     * 更新最后续费信息
     *
     * @param id 自动续费ID
     * @param lastRenewOrderSn 最后续费订单号
     * @param nextRenewTime 下次续费时间
     * @return 结果
     */
    @Override
    public int updateLastRenewInfo(Long id, String lastRenewOrderSn, LocalDateTime nextRenewTime)
    {
        return vipAutoRenewMapper.updateLastRenewInfo(id, lastRenewOrderSn, nextRenewTime);
    }

    /**
     * 批量删除VIP自动续费
     *
     * @param ids 需要删除的VIP自动续费主键
     * @return 结果
     */
    @Override
    public int deleteVipAutoRenewByIds(Long[] ids)
    {
        return vipAutoRenewMapper.deleteVipAutoRenewByIds(ids);
    }

    /**
     * 删除VIP自动续费信息
     *
     * @param id VIP自动续费主键
     * @return 结果
     */
    @Override
    public int deleteVipAutoRenewById(Long id)
    {
        return vipAutoRenewMapper.deleteVipAutoRenewById(id);
    }

    /**
     * 创建自动续费订单
     *
     * @param vipAutoRenew 自动续费记录
     * @return 结果
     */
    @Override
    @Transactional
    public boolean createAutoRenewOrder(VipAutoRenew vipAutoRenew)
    {
        try {
            log.info("开始为用户 {} 创建自动续费订单", vipAutoRenew.getUserId());

            // 获取VIP配置信息
            FhRechargeData rechargeData = fhRechargeDataService.selectById(vipAutoRenew.getRechargeDataId());
            if (rechargeData == null) {
                log.error("未找到充值配置信息，rechargeDataId: {}", vipAutoRenew.getRechargeDataId());
                incrementRetryCount(vipAutoRenew.getId(), "未找到充值配置信息");
                return false;
            }

            // 创建VIP订单
            VipOrder vipOrder = vipOrderService.createVipOrder(
                vipAutoRenew.getUserId(),
                vipAutoRenew.getRechargeDataId(),
                vipAutoRenew.getVipDays(),
                vipAutoRenew.getAmount(),
                vipAutoRenew.getAmount(), // payAmount 与 amount 相同
                vipAutoRenew.getPayType(),
                false // 自动续费订单不再开启自动续费
            );

            if (vipOrder == null) {
                log.error("创建VIP订单失败，用户ID: {}", vipAutoRenew.getUserId());
                incrementRetryCount(vipAutoRenew.getId(), "创建VIP订单失败");
                return false;
            }

            log.info("自动续费订单创建成功，订单号: {}", vipOrder.getOrderSn());

            // TODO: 调用微信支付API进行自动扣费
            // 这里需要根据实际的微信支付SDK来实现
            boolean paymentResult = processWechatAutoPayment(vipOrder, vipAutoRenew);

            if (paymentResult) {
                // 计算下次续费时间（当前VIP到期前3天）
                LocalDateTime nextRenewTime = calculateNextRenewTime(vipAutoRenew.getUserId(), vipAutoRenew.getVipDays());

                // 更新续费记录
                updateLastRenewInfo(vipAutoRenew.getId(), vipOrder.getOrderSn(), nextRenewTime);

                log.info("自动续费成功，用户ID: {}, 订单号: {}", vipAutoRenew.getUserId(), vipOrder.getOrderSn());
                return true;
            } else {
                incrementRetryCount(vipAutoRenew.getId(), "微信支付失败");
                return false;
            }

        } catch (Exception e) {
            log.error("创建自动续费订单异常，用户ID: {}", vipAutoRenew.getUserId(), e);
            incrementRetryCount(vipAutoRenew.getId(), "系统异常: " + e.getMessage());
            return false;
        }
    }

    /**
     * 处理微信自动支付
     *
     * @param vipOrder VIP订单
     * @param vipAutoRenew 自动续费记录
     * @return 支付结果
     */
    private boolean processWechatAutoPayment(VipOrder vipOrder, VipAutoRenew vipAutoRenew)
    {
        try {
            log.info("处理微信自动支付，订单号: {}，合约ID: {}", vipOrder.getOrderSn(), vipAutoRenew.getWechatContractId());

            // 检查是否有有效的签约信息
            if (vipAutoRenew.getWechatContractId() == null ||
                vipAutoRenew.getContractStatus() == null ||
                vipAutoRenew.getContractStatus() != 1) {
                log.error("微信委托代扣签约信息无效，无法进行自动扣费，用户ID: {}", vipAutoRenew.getUserId());
                return false;
            }

            // 调用微信委托代扣API
            Map<String, Object> payResult = wechatPayService.contractPay(
                    vipAutoRenew.getWechatContractId(),
                    vipOrder.getOrderSn(),
                    vipOrder.getAmount(),
                    "VIP自动续费-" + vipOrder.getOrderSn(),
                    null
            );

            if (payResult != null && "SUCCESS".equals(payResult.get("return_code"))) {
                String resultCode = (String) payResult.get("result_code");
                if ("SUCCESS".equals(resultCode)) {
                    log.info("微信委托代扣支付成功，订单号: {}，交易号: {}",
                             vipOrder.getOrderSn(), payResult.get("transaction_id"));

                    // 更新订单状态为已支付
                    vipOrder.setStatus(2); // 2表示已支付
                    vipOrder.setPayTime(LocalDateTime.now());
                    vipOrderService.updateVipOrder(vipOrder);

                    return true;
                } else {
                    String errCodeDes = (String) payResult.get("err_code_des");
                    log.error("微信委托代扣支付失败，订单号: {}，错误描述: {}", vipOrder.getOrderSn(), errCodeDes);
                    return false;
                }
            } else {
                log.error("微信委托代扣API调用失败，订单号: {}，返回结果: {}", vipOrder.getOrderSn(), payResult);
                return false;
            }

        } catch (Exception e) {
            log.error("处理微信自动支付异常，订单号: {}，错误信息: {}", vipOrder.getOrderSn(), e.getMessage(), e);
            return false;
        }
    }

    /**
     * 计算下次续费时间
     *
     * @param userId 用户ID
     * @param vipDays VIP天数
     * @return 下次续费时间
     */
    private LocalDateTime calculateNextRenewTime(Long userId, Integer vipDays)
    {
        // TODO: 根据用户当前VIP到期时间计算下次续费时间
        // 这里需要查询用户信息获取VIP到期时间，然后减去3天
        return LocalDateTime.now().plusDays(vipDays - 3);
    }

    /**
     * 处理自动续费任务
     *
     * @return 处理的记录数
     */
    @Override
    public int processAutoRenewTasks()
    {
        log.info("开始处理自动续费任务");

        LocalDateTime currentTime = LocalDateTime.now();
        List<VipAutoRenew> renewList = selectVipAutoRenewForRenewal(currentTime);

        int processedCount = 0;
        for (VipAutoRenew vipAutoRenew : renewList) {
            try {
                boolean result = createAutoRenewOrder(vipAutoRenew);
                if (result) {
                    processedCount++;
                }
            } catch (Exception e) {
                log.error("处理自动续费任务异常，ID: {}", vipAutoRenew.getId(), e);
            }
        }

        log.info("自动续费任务处理完成，共处理 {} 条记录", processedCount);
        return processedCount;
    }

    /**
     * 取消用户的自动续费
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public boolean cancelAutoRenewByUserId(Long userId)
    {
        try {
            VipAutoRenew vipAutoRenew = selectVipAutoRenewByUserId(userId);
            if (vipAutoRenew != null) {
                updateVipAutoRenewStatus(vipAutoRenew.getId(), 0); // 0表示已取消
                log.info("用户 {} 的自动续费已取消", userId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("取消用户自动续费异常，用户ID: {}", userId, e);
            return false;
        }
    }
}
